import { cleanPath } from './utils/path'
import Regexp from 'path-to-regexp'

export function createRouteMap (routes) {
  const pathList = []
  const pathMap = Object.create(null)
  const nameMap = Object.create(null)

  routes.forEach(item => {
    addRouteRecord(pathList, pathMap, nameMap, item)
  })
  return { pathList, pathMap, nameMap }
}

function addRouteRecord (pathList, pathMap, nameMap, route) {
  const { path, name } = route

  const normalizedPath = normalizePath(path, parent)

  const record = {
    path: normalizedPath,
    regex: compileRouteRegex(normalizedPath, {}),
    components: route.components || { default: route.component },
    name,
    beforeEnter: route.beforeEnter,
    props: {}
  }

  if (!pathMap[record.path]) {
    pathList.push(record.path)
    pathMap[record.path] = record
  }

  if (name) {
    nameMap[name] = (record)
  }
}

function compileRouteRegex (path, options) {
  return Regexp(path, [], options)
}

function normalizePath (path, parent) {
  if (path[0] === '/') {
    // 例如：/about
    return path
  }
  if (!parent) {
    return parent
  }
  cleanPath(`${parent.path}/${path}`)
}
